package com.uzai.console.service.wechatprivate.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.KefuSendMsgEnum;
import com.uzai.common.enums.MessageFuncEnum;
import com.uzai.common.enums.MessageTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.rocketmq.wxgroup.*;
import com.uzai.console.dto.wechatprivate.wxq.wxgroup.*;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupmenber.WxGroupMemberKickDto;
import com.uzai.console.dto.wechatwork.wxq.wxgroup.AddManagerDto;
import com.uzai.console.dto.wechatwork.wxq.wxgroup.BatchAddManagerDto;
import com.uzai.console.entity.ConfigPlan;
import com.uzai.console.entity.DeviceAuth;
import com.uzai.console.entity.DeviceWechatInfo;
import com.uzai.console.entity.SysPlugin;
import com.uzai.console.entity.es.EsWxContacts;
import com.uzai.console.enums.DeviceProductEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiImClientFeignService;
import com.uzai.console.service.feign.WxContactsFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.wechatprivate.WxGroupMemberService;
import com.uzai.console.service.wechatprivate.WxGroupService;
import com.uzai.console.vo.wechatprivate.wxcontacts.WxContactsInfoVo;
import com.uzai.console.vo.wechatprivate.wxq.wxgroup.WxGroupInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.CardinalityAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 个人微信-微信群
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class WxGroupServiceImpl implements WxGroupService {

    Logger logger = LoggerFactory.getLogger(WxGroupServiceImpl.class);

    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private WxContactsFeignService wxContactsFeignService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxqGroupManagePlanMapper wxqGroupManagePlanMapper;
    @Autowired
    private WxqManagePlanMapper wxqManagePlanMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private DeviceAuthMapper deviceAuthMapper;
    @Autowired
    private UzaiImClientFeignService uzaiImClientFeignService;
    @Autowired
    private WxGroupMemberService wxGroupMemberService;

    /**
     * 查询微信群列表
     *
     * @param wxGroupQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<WxGroupInfoVo> findWxGroupList(WxGroupQuery wxGroupQuery) {
        //新建返回到页面的LIST对象
        List<WxGroupInfoVo> wxGroupInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<WxGroupInfoVo> page = new Page<>();
        wxGroupQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or_deviceList = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or_keyword = QueryBuilders.boolQuery();
        //BoolQueryBuilder boolQuery_or_groupIdExcludeList = QueryBuilders.boolQuery();
        //BoolQueryBuilder boolQuery_or_wxidExcludeList = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery_and.must(QueryBuilders.termQuery("merId", Tools.getLong(wxGroupQuery.getMerId())));

        //好友类型(0-个人微信；1-微信群)
        if(wxGroupQuery.getUserType() != null){
            boolQuery_and.must(QueryBuilders.termQuery("userType", wxGroupQuery.getUserType()));
        }

        //微信群id
        if(StringUtils.isNotBlank(wxGroupQuery.getWxid())){
            boolQuery_and.must(QueryBuilders.termQuery("wxid", wxGroupQuery.getWxid()));
        }

        //微信群昵称
        if(StringUtils.isNotBlank(wxGroupQuery.getNick())){
            boolQuery_or_keyword.must(QueryBuilders.termQuery("wxid", wxGroupQuery.getNick()));
            //boolQuery_and.must(QueryBuilders.matchQuery("nick",wxGroupQuery.getNick()));
            //支持中文分词
//            boolQuery_or_keyword.should(QueryBuilders.matchQuery("nick", wxGroupQuery.getNick()));
//            boolQuery_or_keyword.should(QueryBuilders.matchQuery("remark", wxGroupQuery.getNick()));

            //支持数字和英文
            boolQuery_or_keyword.should(QueryBuilders.wildcardQuery("nick.keyword", "*"+wxGroupQuery.getNick() +"*"));
            boolQuery_or_keyword.should(QueryBuilders.wildcardQuery("remark.keyword", "*"+wxGroupQuery.getNick() +"*"));
        }

        //机器人唯一ID
        if(wxGroupQuery.getDeviceUniqueId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId", wxGroupQuery.getDeviceUniqueId()));
        }

        //开启过滤未配置管理方案的群
        if(Tools.getInteger(wxGroupQuery.getManagePlanIdFlag()).intValue() == 1){
            boolQuery_and.must(QueryBuilders.rangeQuery("managePlanId").gte(0));
        }

        //管理方案方案id
        if(wxGroupQuery.getManagePlanId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("managePlanId", wxGroupQuery.getManagePlanId()));
        }

        //排除群id(id主键)
        List<String> groupIdExcludeList = wxGroupQuery.getGroupIdExcludeList();
        if(groupIdExcludeList != null && groupIdExcludeList.size() > 0){
            for (String groupId : groupIdExcludeList) {
                boolQuery_and.mustNot(QueryBuilders.termQuery("id", groupId));
            }
        }

        //排除群wxid
        List<String> wxidExcludeList = wxGroupQuery.getWxidExcludeList();
        if(wxidExcludeList != null && wxidExcludeList.size() > 0){
            for (String wxid : wxidExcludeList) {
                boolQuery_and.mustNot(QueryBuilders.termQuery("wxid", wxid));
            }
        }

        //机器人唯一id列表
        List<Long> deviceUniqueIdList = wxGroupQuery.getDeviceUniqueIdList();
        if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : deviceUniqueIdList) {
                boolQuery_or_deviceList.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //子账号绑定机器人
        List<Long> subDeviceUniqueIdList = wxGroupQuery.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : subDeviceUniqueIdList) {
                boolQuery_or.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //关键词搜索-群昵称
        if(StringUtils.isNotBlank(wxGroupQuery.getKeyword())){
            boolQuery_or_keyword.should(QueryBuilders.termQuery("wxid", wxGroupQuery.getKeyword()));
//            //支持中文分词
//            boolQuery_or_keyword.should(QueryBuilders.matchQuery("nick", wxGroupQuery.getKeyword()));
//            boolQuery_or_keyword.should(QueryBuilders.matchQuery("remark", wxGroupQuery.getKeyword()));
            //支持数字和英文
            boolQuery_or_keyword.should(QueryBuilders.wildcardQuery("nick.keyword", "*"+wxGroupQuery.getKeyword() +"*"));
            boolQuery_or_keyword.should(QueryBuilders.wildcardQuery("remark.keyword", "*"+wxGroupQuery.getKeyword() +"*"));
        }

        searchSourceBuilder.query(boolQuery_and.must(boolQuery_or).must(boolQuery_or_deviceList).must(boolQuery_or_keyword));

        searchSourceBuilder.sort("createTime", SortOrder.DESC);

        //searchSourceBuilder.query(boolQuery_and.must(boolQuery_or).must(boolQuery_or_deviceList).mustNot(boolQuery_or_groupIdExcludeList).mustNot(boolQuery_or_wxidExcludeList));

        //判断根据群wxid去重
        //去重计数字段
        String distinctCount = "distinctCount";
        if(Tools.getInteger(wxGroupQuery.getWxidDistinctFlag()).intValue() == 1){//去重
            //需要去重的字段名
            CollapseBuilder collapseBuilder = new CollapseBuilder("wxid");//针对群wxid字段去重
            //查询去重后的结果数量计数（前者参数为计数自定义名字，后者参数为指定需要计数的字段）
            CardinalityAggregationBuilder aggregationBuilder = AggregationBuilders.cardinality(distinctCount).field("wxid");
            searchSourceBuilder.collapse(collapseBuilder);
            searchSourceBuilder.aggregation(aggregationBuilder);
        }

        //logger.info(searchSourceBuilder.toString());

        String esName = EsIndexName.UZAI_WX_CONTACTS;
        String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, wxGroupQuery.getMerId());

        ESResult esResult = null;
        //去重则从去重当中查询
        if(Tools.getInteger(wxGroupQuery.getWxidDistinctFlag()).intValue() == 1){
            esResult = elasticsearchUtilGroupMsg.distinctSearchListData(mechantOtherEsIndexName, searchSourceBuilder, wxGroupQuery.getSize(), wxGroupQuery.getFromIndex(), null, null, null, wxGroupQuery.getMerId(),distinctCount);
        }else{
            esResult = elasticsearchUtilGroupMsg.searchListData(mechantOtherEsIndexName, searchSourceBuilder, wxGroupQuery.getSize(), wxGroupQuery.getFromIndex(), null, null, null, wxGroupQuery.getMerId());
        }

        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxGroupInfoVo wxGroupInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxGroupInfoVo.class);
                //机器人信息
                DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wxGroupInfoVo.getDeviceUniqueId(), wxGroupInfoVo.getMerId());
                if(deviceWechatInfo != null){
                    wxGroupInfoVo.setDeviceName(deviceWechatInfo.getDeviceName());
                    wxGroupInfoVo.setDeviceRemark(deviceWechatInfo.getDeviceRemark());
                }

                //管理方案信息
                //WxqGroupManagePlan wxqGroupManagePlan = wxqGroupManagePlanMapper.selectByWxidAndDeviceUniqueIdAndMerId(wxGroupInfoVo.getWxid(), wxGroupInfoVo.getDeviceUniqueId(), wxGroupInfoVo.getMerId());
                //WxqGroupManagePlan wxqGroupManagePlan = wxqGroupManagePlanMapper.selectById(wxGroupInfoVo.getManagePlanId(), wxGroupInfoVo.getMerId());
                if(wxGroupInfoVo.getManagePlanId() != null) {
                    ConfigPlan configPlan = configPlanMapper.selectById(wxGroupInfoVo.getManagePlanId(), wxGroupInfoVo.getMerId());
                    if(configPlan != null){
                        wxGroupInfoVo.setManagePlanName(configPlan.getName());
                        wxGroupInfoVo.setManageConfigFlag(1); //配置了管理方案
                        //查询配置方案的功能设置
                        if(configPlan.getGroupBasesetId() != null){
                            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), configPlan.getMerId());
                            if(sysPlugin != null){
                                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                                if(jsonObject != null){
                                    //是否开启返利功能
                                    wxGroupInfoVo.setFlSwitch(Tools.getInteger(jsonObject.getInteger("flSwitch")));
                                    //是否开启免单功能
                                    wxGroupInfoVo.setMdSwitch(Tools.getInteger(jsonObject.getInteger("mdSwitch")));
                                    //是否开启发单功能
                                    wxGroupInfoVo.setFdSwitch(Tools.getInteger(jsonObject.getInteger("fdSwitch")));
                                    //是否开启群内提现功能
                                    wxGroupInfoVo.setTxSwitch(Tools.getInteger(jsonObject.getInteger("txSwitch")));
                                }
                            }
                        }
                    }
                }

                //判断是否购买了发单功能
                int now = DateUtil.getNowTime();
                DeviceAuth deviceAuth_fd = deviceAuthMapper.selectByDeviceIdAndProductCode(wxGroupInfoVo.getDeviceId(), DeviceProductEnum.FD.getValue());
                if(deviceAuth_fd != null){
                    if(deviceAuth_fd.getExpireTime() > now){
                        wxGroupInfoVo.setFdBuyFlag(1);
                    }
                }

                //判断是否购买了托功能
                DeviceAuth deviceAuth_tuo = deviceAuthMapper.selectByDeviceIdAndProductCode(wxGroupInfoVo.getDeviceId(), DeviceProductEnum.TUO.getValue());
                if(deviceAuth_tuo != null){
                    if(deviceAuth_tuo.getExpireTime() > now){
                        wxGroupInfoVo.setTuoBuyFlag(1);
                    }
                }

                //从redis中获取群成员个数
                String key = String.format(RedisCacheKeyEnum.WX_GROUP_MEMBER_COUNT.getKey(), wxGroupInfoVo.getWxid());
                Object wx_group_member_count = redisTemplate.opsForValue().get(key);
                if(wx_group_member_count != null){
                    wxGroupInfoVo.setGmCount((Integer)wx_group_member_count);
                }
                wxGroupInfoVoList.add(wxGroupInfoVo);
            }
        }

        //返回到页面分页对象
        page.setRecords(wxGroupInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }


    /**
     * 查询微信群列表
     *
     * @param wxGroupIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public WxGroupInfoVo findWxGroupInfo(WxGroupIdDto wxGroupIdDto){
        WxGroupInfoVo wxGroupInfoVo = new WxGroupInfoVo();
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxGroupIdDto.getMerId());
        Map<String,Object> dataMap = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupIdDto.getId(), null);
        if(dataMap != null){
            wxGroupInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), WxGroupInfoVo.class);
        }

        //从redis中获取群成员个数
        String key = String.format(RedisCacheKeyEnum.WX_GROUP_MEMBER_COUNT.getKey(), wxGroupInfoVo.getWxid());
        Object wx_group_member_count = redisTemplate.opsForValue().get(key);
        if(wx_group_member_count != null){
            wxGroupInfoVo.setGmCount((Integer)wx_group_member_count);
        }

        return wxGroupInfoVo;
    }

    /**
     * 查询微信群列表-根据已经配置了管理方案来查询
     *
     * @param wxqGroupManagePlanQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
//    public Page<WxGroupInfoVo> findWxqGroupManagePlanList(WxqGroupManagePlanQuery wxqGroupManagePlanQuery){

//        //新建返回到页面的LIST对象
//        List<WxGroupInfoVo> wxGroupInfoVoList = new ArrayList<>();
//        //执行分页查询对象
//        Page<WxqGroupManagePlan> page = new Page<>();
//        wxqGroupManagePlanQuery.convert(page);
//        List<WxqGroupManagePlan> wxqGroupManagePlanList = wxqGroupManagePlanMapper.findByList(page, wxqGroupManagePlanQuery);
//
//        if(wxqGroupManagePlanList != null && wxqGroupManagePlanList.size() > 0) {
//            for (WxqGroupManagePlan wxqGroupManagePlan : wxqGroupManagePlanList) {
//                String id = wxqGroupManagePlan.getMerId() + "_" + wxqGroupManagePlan.getDeviceId() + "_" + wxqGroupManagePlan.getWxid();
//
//                String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxqGroupManagePlanQuery.getMerId());
//                Map<String,Object> dataMap = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, id, null);
//                if(dataMap != null){ //存在群ES中
//                    WxGroupInfoVo wxGroupInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), WxGroupInfoVo.class);
//                    if(wxGroupInfoVo != null) {
//
//                        //机器人信息
//                        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wxGroupInfoVo.getDeviceUniqueId(), wxGroupInfoVo.getMerId());
//                        if (deviceWechatInfo != null) {
//                            wxGroupInfoVo.setDeviceName(deviceWechatInfo.getDeviceName());
//                            wxGroupInfoVo.setDeviceRemark(deviceWechatInfo.getDeviceRemark());
//                        }
//
//                        //管理方案信息
//                        ConfigPlan configPlan = configPlanMapper.selectById(wxqGroupManagePlan.getManagePlanId(), wxqGroupManagePlan.getMerId());
//                        if(configPlan != null){
//                            wxGroupInfoVo.setManagePlanId(wxqGroupManagePlan.getManagePlanId());
//                            wxGroupInfoVo.setManagePlanName(configPlan.getName());
//                        }
//
//                        //从redis中获取群成员个数
//                        String key = String.format(RedisCacheKeyEnum.WX_GROUP_MEMBER_COUNT.getKey(), wxGroupInfoVo.getWxid());
//                        Object wx_group_member_count = redisTemplate.opsForValue().get(key);
//                        if(wx_group_member_count != null){
//                            wxGroupInfoVo.setGmCount((Integer)wx_group_member_count);
//                        }
//
//                    }
//                    wxGroupInfoVoList.add(wxGroupInfoVo);
//                }else{ //不存在，则表示该群不存在，则需要自动清理该管理方案微信群
//                    wxqGroupManagePlanMapper.deleteById(wxqGroupManagePlan.getId(), wxqGroupManagePlan.getMerId());
//                    //删除缓存中的微信群管理方案key
//                    String redisKey_wxgroup_manageplan = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), wxqGroupManagePlan.getMerId(), wxqGroupManagePlan.getDeviceId(), wxqGroupManagePlan.getWxid());
//                    redisTemplate.delete(redisKey_wxgroup_manageplan);
//                }
//            }
//        }
//
//        //返回页面的page
//        //执行分页查询对象
//        Page<WxGroupInfoVo> pageResult = new Page<>();
//        wxqGroupManagePlanQuery.convert(pageResult);
//        pageResult.setTotal(page.getTotal());
//        pageResult.setRecords(wxGroupInfoVoList);
//        return pageResult;
//    }

    /**
     * 退群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupIdDto
     * @return null
     */
    public void quitWxGroup(WxGroupIdDto wxGroupIdDto){

        if(wxGroupIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择id");
        }

        //查询微信群
        String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
        uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, wxGroupIdDto.getMerId());

        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupIdDto.getId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
        if(esWxContacts != null){
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(esWxContacts.getDeviceUniqueId(), wxGroupIdDto.getMerId());
            if(deviceWechatInfo != null){
                //发送退群指令MQ消息
                MsgDto<QuitGroupDto> msgDto = new MsgDto<>();
                QuitGroupDto quitGroupDto = new QuitGroupDto();
                quitGroupDto.setGroupId(esWxContacts.getWxid());
                msgDto.setContent(quitGroupDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                msgDto.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
                msgDto.setMerId(wxGroupIdDto.getMerId());
                msgDto.setMsgType(MessageFuncEnum.QUIT_GROUP.getValue());
                noticeMsgPushProducerService.quitWxGroup(msgDto);
            }

            //删除群
            elasticsearchUtilGroupMsg.deleteDataById(uzai_wx_contacts, wxGroupIdDto.getId());

            //判断是否配置了管理方案，如果配置了管理费方案，则需要删除管理方案关系
            if(esWxContacts.getManagePlanId() != null){
                //删除缓存中的微信群管理方案key
                String redisKey_wxgroup_manageplan = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), esWxContacts.getMerId(), esWxContacts.getDeviceId(), esWxContacts.getWxid());
                redisTemplate.delete(redisKey_wxgroup_manageplan);
            }

            //判断是否删除群成员-查询该群id是否存在，如果不存在，则需要删除群成员
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //运营商ID
            boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(wxGroupIdDto.getMerId())));
            //微信群微信id
            boolQuery.must(QueryBuilders.termQuery("wxid", esWxContacts.getWxid()));
            searchSourceBuilder.query(boolQuery);
            WxGroupQuery wxGroupQuery = new WxGroupQuery();
            wxGroupQuery.setMerId(esWxContacts.getMerId());
            wxGroupQuery.setCurrent(1);
            wxGroupQuery.setSize(5);
            String esName = EsIndexName.UZAI_WX_CONTACTS;
            String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, wxGroupQuery.getMerId());
            ESResult esResult = elasticsearchUtilGroupMsg.searchListData(mechantOtherEsIndexName, searchSourceBuilder, wxGroupQuery.getSize(), wxGroupQuery.getFromIndex(), null, null, null, wxGroupQuery.getMerId());

            String uzai_wx_group_member = EsIndexName.UZAI_WX_GROUP_MEMBER;
            uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(uzai_wx_group_member, wxGroupQuery.getMerId());
            if(esResult.getTotalHits() == 0){ //表示没有群了，则需要清除该群所有成员
                DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
                //清空所有的发送明细
                SearchSourceBuilder searchSourceBuilder_del = new SearchSourceBuilder();
                BoolQueryBuilder boolQuery_and = new BoolQueryBuilder();
                //运营商ID
                boolQuery_and.must(QueryBuilders.termQuery("merId", Tools.getLong(wxGroupIdDto.getMerId())));
                //群微信id
                boolQuery_and.must(new TermQueryBuilder("groupWxid", esWxContacts.getWxid()));
                searchSourceBuilder_del.query(boolQuery_and).size(100);
                deleteByQueryRequest.getSearchRequest().source(searchSourceBuilder_del);
                elasticsearchUtilGroupMsg.deleteDataByQueryMulti(uzai_wx_group_member, deleteByQueryRequest);
            }else{ //只清除该群内该机器人成员自己
                String id = wxGroupIdDto.getMerId() + "_" + esWxContacts.getWxid() + "_" + esWxContacts.getDeviceId();
                elasticsearchUtilGroupMsg.deleteDataById(uzai_wx_group_member, id);
            }
        }
    }

    /**
     * 单个发送消息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupSendMessageDto
     * @return null
     */
    public void sendMessage(WxGroupSendMessageDto wxGroupSendMessageDto){

        if(StringUtils.isBlank(wxGroupSendMessageDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        if(StringUtils.isBlank(wxGroupSendMessageDto.getMessage())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入消息内容");
        }

        //查询微信群
        //查询微信群
        String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
        uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, wxGroupSendMessageDto.getMerId());

        Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupSendMessageDto.getId(), null);
        EsWxContacts esWxContacts = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
        if (esWxContacts != null) {

            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(esWxContacts.getDeviceUniqueId(), wxGroupSendMessageDto.getMerId());
            if(deviceWechatInfo != null){
                //发送MQ消息
                MsgDto<NoticeMsgDto>  msgDto = new MsgDto<>();
                NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                noticeMsgDto.setBizUserId(esWxContacts.getWxid());
                noticeMsgDto.setContent(wxGroupSendMessageDto.getMessage());
                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                noticeMsgDto.setGroupId(null);
                noticeMsgDto.setNickName(esWxContacts.getNick());
                noticeMsgDto.setMsgSource(1);
                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                msgDto.setContent(noticeMsgDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                msgDto.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
                msgDto.setMerId(wxGroupSendMessageDto.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                noticeMsgPushProducerService.sendMessage(msgDto);
            }
        }
    }

    /**
     * 修改管理方案
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupUpdateManagePlanDto
     * @return null
     */
    public void updateManagePlan(WxGroupUpdateManagePlanDto wxGroupUpdateManagePlanDto){
        if(StringUtils.isBlank(wxGroupUpdateManagePlanDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }


        //查询微信群
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxGroupUpdateManagePlanDto.getMerId());

        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupUpdateManagePlanDto.getId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        int now = DateUtil.getNowTime();

        //缓存中的微信群管理方案key
        String redisKey_wxgroup_manageplan = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), esWxContacts.getMerId(), esWxContacts.getDeviceId(), esWxContacts.getWxid());
        //如果管理方案为空，则表示清空管理方案
        if(wxGroupUpdateManagePlanDto.getManagePlanId() == null){ //清除管理方案

            //清除ES
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("managePlanId", null); //清除ES
//            jsonObject.put("updateTime", now);
//            elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_wx_contacts, esWxContacts.getId());


            esWxContacts.setManagePlanId(null);
            esWxContacts.setUpdateTime(now);
            elasticsearchUtilGroupMsg.addData(esWxContacts, uzai_wx_contacts, esWxContacts.getId());

            //清除缓存
            redisTemplate.delete(redisKey_wxgroup_manageplan);

        } else {//修改管理方案
            //修改ES
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("managePlanId", wxGroupUpdateManagePlanDto.getManagePlanId());
//            jsonObject.put("updateTime", now);
//            elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_wx_contacts, esWxContacts.getId());

            esWxContacts.setManagePlanId(wxGroupUpdateManagePlanDto.getManagePlanId());
            esWxContacts.setUpdateTime(now);
            elasticsearchUtilGroupMsg.addData(esWxContacts, uzai_wx_contacts, esWxContacts.getId());

            //修改缓存
            redisTemplate.opsForValue().set(redisKey_wxgroup_manageplan, wxGroupUpdateManagePlanDto.getManagePlanId());
        }
    }

    /**
     * 批量修改管理方案
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupBatchUpdateManagePlanDto
     * @return null
     */
    public void batchUpdateManagePlan(WxGroupBatchUpdateManagePlanDto wxGroupBatchUpdateManagePlanDto){
        //微信群id列表
        List<String> idList = wxGroupBatchUpdateManagePlanDto.getIdList();
        //管理方案
        Long managePlanId = wxGroupBatchUpdateManagePlanDto.getManagePlanId();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量操作的微信群");
        }
        for(String id  : idList){
            try {
                WxGroupUpdateManagePlanDto wxGroupUpdateManagePlanDto = new WxGroupUpdateManagePlanDto();
                BeanUtils.copyProperties(wxGroupBatchUpdateManagePlanDto, wxGroupUpdateManagePlanDto);
                wxGroupUpdateManagePlanDto.setMerId(wxGroupBatchUpdateManagePlanDto.getMerId());
                wxGroupUpdateManagePlanDto.setId(id);
                wxGroupUpdateManagePlanDto.setManagePlanId(managePlanId);
                updateManagePlan(wxGroupUpdateManagePlanDto);
            }catch (Exception e){

            }
        }
    }

    /**
     * 单个刷新群成员
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupIdDto
     * @return null
     */
    public void refreshGroupMember(WxGroupIdDto wxGroupIdDto){
        if(StringUtils.isBlank(wxGroupIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询微信群
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxGroupIdDto.getMerId());

        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupIdDto.getId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(esWxContacts.getDeviceUniqueId(), wxGroupIdDto.getMerId());
        if(deviceWechatInfo != null){
            //发送MQ消息
            //发送刷新成员列表指令MQ消息
            MsgDto<GetGroupMemberListDto> msgDto = new MsgDto<>();
            GetGroupMemberListDto getGroupMemberListDto = new GetGroupMemberListDto();
            getGroupMemberListDto.setGroupId(esWxContacts.getWxid());
            msgDto.setContent(getGroupMemberListDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
            msgDto.setMerId(wxGroupIdDto.getMerId());
            msgDto.setMsgType(MessageFuncEnum.GET_GROUP_MEMBER_LIST.getValue());
            noticeMsgPushProducerService.getGroupMemberList(msgDto);
        }
    }

    /**
     * 修改群名称
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupUpdateNicknameDto
     * @return null
     */
    public void updateWxGroupNickName(WxGroupUpdateNicknameDto wxGroupUpdateNicknameDto){
        if(StringUtils.isBlank(wxGroupUpdateNicknameDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        if(StringUtils.isBlank(wxGroupUpdateNicknameDto.getGroupName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入群名称");
        }

        //查询
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxGroupUpdateNicknameDto.getMerId());

        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupUpdateNicknameDto.getId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群不存在");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(esWxContacts.getDeviceUniqueId(), wxGroupUpdateNicknameDto.getMerId());
        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群机器人未找到");
        }

        //调用微服务更新群名称
        MsgDto<UpdateNicknameDto> msgDto = new MsgDto<>();
        UpdateNicknameDto updateNicknameDto = new UpdateNicknameDto();
        updateNicknameDto.setGroupId(esWxContacts.getWxid());
        updateNicknameDto.setNewGroupName(wxGroupUpdateNicknameDto.getGroupName());
        msgDto.setContent(updateNicknameDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
        msgDto.setMerId(wxGroupUpdateNicknameDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.SET_GROUP_NAME.getValue());
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.setGroupName(msgDto);
        logger.info("--调用个人微信群名称接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }

        //修改通讯录群昵称
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("nick", wxGroupUpdateNicknameDto.getGroupName()); //延迟数
        elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_wx_contacts, wxGroupUpdateNicknameDto.getId());

        //延迟1秒
        try {
            Thread.sleep(1000);
        }catch (Exception e){

        }

    }

    /**
     * 创建群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupCreateDto
     * @return null
     */
    public void createWxGroup(WxGroupCreateDto wxGroupCreateDto){
        if(wxGroupCreateDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人唯一id");
        }

        if(StringUtils.isBlank(wxGroupCreateDto.getGroupName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入群昵称");
        }

        List<String> memberIdList = wxGroupCreateDto.getMemberIdList();
        if(memberIdList == null || memberIdList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择成员");
        }
        if(memberIdList.size() >= 40){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "成员必须少于40个");
        }
        //成员id列表
        List<String> wxidList = new ArrayList<>();
        //查询通讯录
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxGroupCreateDto.getMerId());
        for (String memberId : memberIdList) {
            //查询该成员信息
            Map<String,Object> dataMp_contacts = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, memberId, null);
            WxContactsInfoVo wxContactsInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_contacts)), WxContactsInfoVo.class);
            if(wxContactsInfoVo != null){
                wxidList.add(wxContactsInfoVo.getWxid());
            }
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wxGroupCreateDto.getDeviceUniqueId(), wxGroupCreateDto.getMerId());
        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群机器人未找到");
        }

        //调用微服务创建群
        MsgDto<CreateWxworkGroupDto> msgDto = new MsgDto<>();
        CreateWxworkGroupDto createWxworkGroupDto = new CreateWxworkGroupDto();
        createWxworkGroupDto.setGroupName(wxGroupCreateDto.getGroupName());
        createWxworkGroupDto.setArrWxids(String.join(";", wxidList));
        msgDto.setContent(createWxworkGroupDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(wxGroupCreateDto.getDeviceUniqueId());
        msgDto.setMerId(wxGroupCreateDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.CREATE_GROUP.getValue());

        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.createGroup(msgDto);
        logger.info("--调用创建个人微信群接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 邀请入群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupInviteDto
     * @return null
     */
    public void inviteWxGroup(WxGroupInviteDto wxGroupInviteDto){
        if(StringUtils.isBlank(wxGroupInviteDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        List<String> memberIdList = wxGroupInviteDto.getMemberIdList();
        if(memberIdList == null || memberIdList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择成员");
        }
        if(memberIdList.size() >= 40){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "成员必须少于40个");
        }
        //成员id列表
        List<String> wxidList = new ArrayList<>();
        //查询通讯录
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxGroupInviteDto.getMerId());
        for (String memberId : memberIdList) {
            //查询该成员信息
            Map<String,Object> dataMp_contacts = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, memberId, null);
            WxContactsInfoVo wxContactsInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_contacts)), WxContactsInfoVo.class);
            if(wxContactsInfoVo != null){
                wxidList.add(wxContactsInfoVo.getWxid());
            }
        }

        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupInviteDto.getId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群不存在");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(esWxContacts.getDeviceUniqueId(), wxGroupInviteDto.getMerId());
        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群机器人未找到");
        }


        //调用微服务邀请入群
        MsgDto<InviteWxworkGroupDto> msgDto = new MsgDto<>();
        InviteWxworkGroupDto inviteWxworkGroupDto = new InviteWxworkGroupDto();
        inviteWxworkGroupDto.setGroupId(esWxContacts.getWxid());
        inviteWxworkGroupDto.setArrWxids(String.join(";", wxidList));
        inviteWxworkGroupDto.setInviteType(0); //拉人进群
        msgDto.setContent(inviteWxworkGroupDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
        msgDto.setMerId(wxGroupInviteDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.INVITE_TO_GROUP.getValue());

        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.inviteJoinGroup(msgDto);
        logger.info("--调用个人微信邀请入群接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 批量邀请入群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupBatchInviteDto
     * @return null
     */
    public void batchInviteWxGroup(WxGroupBatchInviteDto wxGroupBatchInviteDto){
        //微信群id列表
        List<String> idList = wxGroupBatchInviteDto.getIdList();
        //入群微信id列表
        List<String> memberIdList = wxGroupBatchInviteDto.getMemberIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量操作的微信群");
        }

        if(memberIdList == null || memberIdList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量入群人员");
        }

        if(memberIdList.size() >= 40){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "成员必须少于40个");
        }

        for(String id  : idList){
            try {
                WxGroupInviteDto wxGroupInviteDto = new WxGroupInviteDto();
                BeanUtils.copyProperties(wxGroupBatchInviteDto, wxGroupInviteDto);
                wxGroupInviteDto.setMerId(wxGroupBatchInviteDto.getMerId());
                wxGroupInviteDto.setId(id);
                wxGroupInviteDto.setMemberIdList(wxGroupBatchInviteDto.getMemberIdList());
                inviteWxGroup(wxGroupInviteDto);
            }catch (Exception e){
                logger.error("--批量入群错误，err={}",e.getMessage());
            }
        }
    }

    /**
     * 发送群公告
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupSendNoticeDto
     * @return null
     */
    public void sendNotice(WxGroupSendNoticeDto wxGroupSendNoticeDto){
        if(StringUtils.isBlank(wxGroupSendNoticeDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        if(StringUtils.isBlank(wxGroupSendNoticeDto.getNotice())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入群公告");
        }

        //查询微信群
        //查询通讯录
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxGroupSendNoticeDto.getMerId());
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupSendNoticeDto.getId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群不存在");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(esWxContacts.getDeviceUniqueId(), wxGroupSendNoticeDto.getMerId());
        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群机器人未找到");
        }

        //调用发送群公告接口
        MsgDto<SendGroupNoticeDto> msgDto = new MsgDto<>();
        SendGroupNoticeDto sendGroupNoticeDto = new SendGroupNoticeDto();
        sendGroupNoticeDto.setGroupId(esWxContacts.getWxid());
        sendGroupNoticeDto.setContent(wxGroupSendNoticeDto.getNotice());
        msgDto.setContent(sendGroupNoticeDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
        msgDto.setMerId(wxGroupSendNoticeDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.SEND_GROUP_NOTICE.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.sendGroupNotice(msgDto);
        logger.info("--调用发送个人微信群公告接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 批量发送群公告
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupBatchSendNoticeDto
     * @return null
     */
    public void batchSendNotice(WxGroupBatchSendNoticeDto wxGroupBatchSendNoticeDto){
        //微信群id列表
        List<String> idList = wxGroupBatchSendNoticeDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量操作的微信群");
        }

        if(Strings.isBlank(wxGroupBatchSendNoticeDto.getNotice())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入公告信息");
        }

        for(String id  : idList){
            try {
                WxGroupSendNoticeDto wxGroupSendNoticeDto = new WxGroupSendNoticeDto();
                BeanUtils.copyProperties(wxGroupBatchSendNoticeDto, wxGroupSendNoticeDto);
                wxGroupSendNoticeDto.setMerId(wxGroupBatchSendNoticeDto.getMerId());
                wxGroupSendNoticeDto.setId(id);
                wxGroupSendNoticeDto.setNotice(wxGroupBatchSendNoticeDto.getNotice());
                sendNotice(wxGroupSendNoticeDto);
            }catch (Exception e){
                logger.error("--个人微信群发公告批量操作错误，err={}",e.getMessage());
            }
        }
    }

    /**
     * 刷新成员
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupIdDto
     * @return null
     */
    public void refreshMember(WxGroupIdDto wxGroupIdDto){
        if(StringUtils.isBlank(wxGroupIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询微信群
        //查询通讯录
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxGroupIdDto.getMerId());
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupIdDto.getId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群不存在");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(esWxContacts.getDeviceUniqueId(), wxGroupIdDto.getMerId());
        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群机器人未找到");
        }

        //发送刷新成员列表指令MQ消息
        MsgDto<GetGroupMemberListDto> msgDto = new MsgDto<>();
        GetGroupMemberListDto getGroupMemberListDto = new GetGroupMemberListDto();
        getGroupMemberListDto.setGroupId(esWxContacts.getWxid());
        msgDto.setContent(getGroupMemberListDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
        msgDto.setMerId(wxGroupIdDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.GET_GROUP_MEMBER_LIST.getValue());
        noticeMsgPushProducerService.getGroupMemberList(msgDto);
        logger.info("--发送刷新个人微信群成员MQ消息--para={}",JSONObject.toJSONString(msgDto));
    }

    /**
     * 企业微信批量踢出群成员
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param batchKickWxGroupMemberDto
     * @return null
     */
    public void batchKickWxGroupMember(BatchKickWxGroupMemberDto batchKickWxGroupMemberDto){
        //微信群id列表
        List<String> idList = batchKickWxGroupMemberDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量操作的微信群");
        }

        List<String> wxidList = batchKickWxGroupMemberDto.getWxidList();

        if(wxidList == null || wxidList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择成员微信id");
        }

        if(wxidList.size() >= 40){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "每次批量操作必须少于40个");
        }

        for(String id  : idList){
            try {
                WxGroupMemberKickDto wxGroupMemberKickDto = new WxGroupMemberKickDto();
                BeanUtils.copyProperties(batchKickWxGroupMemberDto, wxGroupMemberKickDto);
                wxGroupMemberKickDto.setMerId(batchKickWxGroupMemberDto.getMerId());
                wxGroupMemberKickDto.setGroupId(id);
                wxGroupMemberKickDto.setWxidList(batchKickWxGroupMemberDto.getWxidList());
                wxGroupMemberKickDto.setQuitReason(batchKickWxGroupMemberDto.getQuitReason());
                wxGroupMemberService.kickWxGroupMember(wxGroupMemberKickDto);
            }catch (Exception e){
                logger.error("--批量操作错误，err={}",e.getMessage());
            }
        }
    }

    /**
     * 修改微信群备注
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupUpdateRemarkDto
     * @return null
     */
    public void updateRemark(WxGroupUpdateRemarkDto wxGroupUpdateRemarkDto){
        if(StringUtils.isBlank(wxGroupUpdateRemarkDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxGroupUpdateRemarkDto.getMerId());

        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupUpdateRemarkDto.getId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群不存在");
        }

        //修改通讯录群昵称
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("remark", wxGroupUpdateRemarkDto.getRemark()); //群备注
        elasticsearchUtilGroupMsg.updateDataNullById(jsonObject, uzai_wx_contacts, wxGroupUpdateRemarkDto.getId());

        //延迟1秒
        try {
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    @Override
    public void batchAddManager(BatchAddManagerDto batchAddManagerDto) {
        if(batchAddManagerDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商ID不能为空");
        }
        if(batchAddManagerDto.getIdList()==null||batchAddManagerDto.getIdList().isEmpty()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        if(batchAddManagerDto.getWxidList()==null||batchAddManagerDto.getWxidList().isEmpty()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        if(batchAddManagerDto.getWxidList().size()>3){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最多设置3个管理员");
        }
        for(String id  : batchAddManagerDto.getIdList()){
            try {
                List<String> WxIdList = new ArrayList<>();
                for (String wxId : batchAddManagerDto.getWxidList()) {
                    int firstIndex = id.lastIndexOf("_");
                    int secondIndex = id.indexOf("room", firstIndex + 1);
                    String groupId = id.substring(firstIndex + 1, secondIndex + 4);
                    StringBuilder stringBuffer = new StringBuilder();
                    stringBuffer.append(batchAddManagerDto.getMerId());
                    stringBuffer.append("_");
                    stringBuffer.append(groupId);
                    stringBuffer.append("_");
                    stringBuffer.append(wxId);
                    WxIdList.add(stringBuffer.toString());
                }

                AddManagerDto addManagerDto = new AddManagerDto();
                addManagerDto.setMerId(batchAddManagerDto.getMerId());
                addManagerDto.setGroupId(id);
                addManagerDto.setWxidList(WxIdList);
                wxGroupMemberService.addManager(addManagerDto);
            }catch (Exception e){
                logger.error("--批量操作错误，err={}",e.getMessage());
            }
        }
    }
}
